package com.meitianhui.convenitenbuy.module.store.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.module.store.adapter.OneLotteryDskAdapter;
import com.meitianhui.convenitenbuy.module.store.contract.OneLotteryDSKContract;
import com.meitianhui.convenitenbuy.module.store.di.DaggerStoreComponent;
import com.meitianhui.convenitenbuy.module.store.di.StoreModule;
import com.meitianhui.convenitenbuy.module.store.model.DSKBean;
import com.meitianhui.convenitenbuy.module.store.model.DskStoreDetailBean;
import com.meitianhui.convenitenbuy.module.store.model.StoreOneLotteryBean;
import com.meitianhui.convenitenbuy.module.store.presenter.OneLotteryDSKPresenter;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxTimerUtils;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.StringUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.PasswordDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import rx.functions.Action1;

import static com.meitianhui.convenitenbuy.R.id.dsk_tv_add;

/**
 * Created by Administrator on 2017/11/24.
 * 一元抽奖之定时开
 */

public class OneLotteryDSKActivity extends BaseToolbarActivity implements OneLotteryDSKContract.View {
    private String mStoreId, mStoreName;

    @Inject
    OneLotteryDSKPresenter presenter;
    private TextView dsk_min_person;
    private ImageView img_goods;
    private ImageView img_shopcar;
    private ImageView img_collect;
    private TextView tv_storename;
    private EditText edit_num;
    private ImageView dsk_img_min;
    private ImageView dsk_img_add;
    private TextView tv_join;
    private TextView tv_good_name;
    private TextView tv_good_type;
    private ProgressBar progressBar;
    private TextView tv_porson;
    private TextView tv_time;
    private RecyclerView mRv;
    private StoreOneLotteryBean.ActivityListEntity entity;
    private String url;
    private RxTimerUtils mRx;
    private int min_second = 0;
    private int getDifftime;
    private RxTimerUtils.IRxNext next;
    private PasswordDialog passwordDialog;
    private int page = 1;
    private OneLotteryDskAdapter mAdapter;
    private boolean iscondet;


    @Override
    protected int setView() {
        return R.layout.activity_one_lottery_dsk;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerStoreComponent
                .builder()
                .appComponent(App.getInstance().getAppComponent())
                .storeModule(new StoreModule(this))
                .build()
                .inject(this);

        initId();
        initData();
        initInfo();
    }

    private void initId() {
        dsk_min_person = getViewById(R.id.dsk_min_person);
        img_goods = getViewById(R.id.dsk_goodimg);
        img_shopcar = getViewById(R.id.dsk_shopcar);
        img_collect = getViewById(R.id.dsk_collect);
        tv_storename = getViewById(R.id.dsk_storename);
        edit_num = getViewById(R.id.dsk_img_num);
        dsk_img_min = getViewById(R.id.dsk_img_min);
        dsk_img_add = getViewById(R.id.dsk_img_add);
        tv_join = getViewById(dsk_tv_add);
        tv_good_name = getViewById(R.id.dsk_title);
        tv_good_type = getViewById(R.id.dsk_goodtype);
        progressBar = getViewById(R.id.dsk_progress);
        tv_porson = getViewById(R.id.dsk_person);
        tv_time = getViewById(R.id.dsk_time);
        mRv = getViewById(R.id.rv_one_lottery_dsk);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRv.setLayoutManager(layoutManager);
        edit_num.setSelection(edit_num.getText().length());
    }

    private void initInfo() {
        presenter.getDskInfo(entity.getActivity_id());
        presenter.getStoreDskInfo(page, entity.getActivity_id());
    }


    private void initData() {
        setTbTitle(getString(R.string.home_one_lottery_participate_type3));
        Intent intent = getIntent();
        mStoreId = intent.getStringExtra("store_id");
        mStoreName = intent.getStringExtra("store_name");
        iscondet = intent.getBooleanExtra("iscondet", true);
        entity = intent.getParcelableExtra(Constants.ARGUMENT);
        url = intent.getStringExtra("url");
        if (iscondet) {
            img_shopcar.setVisibility(View.GONE);
            img_collect.setVisibility(View.GONE);
        }
        tv_storename.setText(mStoreName);
        GlideUtils.setRectImage(this,url, R.mipmap.icon_default_app, R.mipmap.icon_default_app, img_goods);
        RxUtils.bindEvents(img_collect, this);
        RxUtils.bindEvents(img_shopcar, this);
        RxUtils.bindEvents(dsk_img_min, this);
        RxUtils.bindEvents(dsk_img_add, this);
        RxUtils.bindEvents(tv_join, this);
        mRx = new RxTimerUtils();
        next = new RxTimerUtils.IRxNext() {
            @Override
            public void doNext(long number) {
                min_second += 1;
                goToRefreshView();
            }
        };
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.dsk_shopcar:
                Intent intent = new Intent(OneLotteryDSKActivity.this, StoreDetailActivity.class);
                intent.putExtra("storeId", mStoreId);
                startActivity(intent);
                break;
            case R.id.dsk_collect:
                presenter.postFavoriteStore(mStoreId);
                break;
            case R.id.dsk_img_min:
                String num = edit_num.getText().toString().trim();
                try {
                    if (!TextUtils.isEmpty(num) && Integer.parseInt(num) > 1) {
                        edit_num.setText((Integer.parseInt(num) - 1) + "");
                    }

                } catch (Exception e) {
                    LogUtils.e(e.getMessage());
                }
                break;
            case R.id.dsk_img_add:
                String num1 = edit_num.getText().toString().trim();
                try {
                    if (!TextUtils.isEmpty(num1)) {
                        edit_num.setText((Integer.parseInt(num1) + 1) + "");
                    } else {
                        edit_num.setText("1");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.dsk_tv_add:
                SystemUtils.hidKeyBoard(OneLotteryDSKActivity.this);
                if ("已结束".equals(tv_time.getText().toString())) {
                    return;
                }
                String s_edit_num = edit_num.getText().toString().trim();
                if (TextUtils.isEmpty(s_edit_num)) {
                    TipUtils.showToast(OneLotteryDSKActivity.this, "请输入参与人次", 3);
                    return;
                }
                createDialog(s_edit_num);
                break;
        }
    }

    /**
     * 显示参与dialog
     *
     * @param s_edit_num
     */
    private void createDialog(String s_edit_num) {
        Dialog dialog = new Dialog(this, R.style.dialog_custom);
        dialog.setContentView(R.layout.dialog_store_one_lottery);
        RxUtils.bindEvents(dialog.findViewById(R.id.tv_dialog_store_one_lottery), new Action1<View>() {
            @Override
            public void call(View view) {
                dialog.dismiss();
                checkPay(s_edit_num);
            }
        });

        RxUtils.bindEvents(dialog.findViewById(R.id.iv_dialog_store_one_lottery_close), new Action1<View>() {
            @Override
            public void call(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 检测是否需要输入支付密码
     *
     * @param s_edit_num
     */
    private void checkPay(String s_edit_num) {
        UserToken userToken = InfoProvider.getUserToken(App.getInstance());
        if (userToken.getSmall_direct_flag().equals("N") && userToken.getPayment_password_flag().equals("Y")) {
            showPasswordDialog(s_edit_num);
        } else if (userToken.getSmall_direct_flag().equals("Y") && Float.parseFloat("1") > Constants.SMALL_AMOUNT && userToken.getPayment_password_flag().equals("Y")) {
            showPasswordDialog(s_edit_num);
        } else
            presenter.checkDskInfo(entity.getActivity_id(), edit_num.getText().toString().trim());
    }

    /**
     * 显示支付密码
     *
     * @param s_edit_num
     */
    private void showPasswordDialog(String s_edit_num) {
        String all_money = StringUtils.formatMoney(s_edit_num);

        if (passwordDialog == null) {
            passwordDialog = new PasswordDialog(this, R.layout.dialog_payment_pwd);
            passwordDialog.setOnDialogPsdCompareListener(new PasswordDialog.OnDialogPsdCompleteListener() {

                @Override
                public void onPasswordCorrect(PasswordDialog dialog) {
                    passwordDialog.dismiss();
                    payChange(all_money);
                }

                @Override
                public void onPasswordError(PasswordDialog dialog, String msg) {
                    TipUtils.showToast(OneLotteryDSKActivity.this, msg);
                    passwordDialog.clearInput();
                }
            });
        }

        passwordDialog.show();
        passwordDialog.setPsdDescription(getString(R.string.home_one_lottery_pay));
        passwordDialog.setPsdContent(all_money);
    }

    /**
     * 支付
     *
     * @param all_money
     */
    private void payChange(String all_money) {
        if (!StringUtils.moneyComp(InfoProvider.getUserAsset(App.getInstance()).getCash_balance(), all_money)) {
            TipUtils.showToast(App.getInstance(), "余额不足", 3);
            return;
        }
        presenter.checkDskInfo(entity.getActivity_id(), edit_num.getText().toString().trim());

    }

    /**
     * 获取活动基本信息
     *
     * @param result
     * @param msg
     * @param bean
     * @param doc_url
     */
    @Override
    public void getDskInfoBack(boolean result, String msg, DSKBean.ListEntity bean, HashMap<String, String> doc_url) {
        if (result) {
            if (bean != null) {
                getDifftime = bean.getDifftime();
                tv_good_name.setText(bean.getTitle());
                tv_good_type.setText(bean.getAward_name());
                progressBar.setProgress(Integer.parseInt(bean.getTotal_person()) * 100 / Integer.parseInt(bean.getPerson_num()));
                tv_porson.setText("已参与" + bean.getTotal_person() + "人");
                int p_imt = Integer.parseInt(bean.getPerson_num()) - Integer.parseInt(bean.getTotal_person());

                if (p_imt <= 0) {
                    dsk_min_person.setText("已达成");
                } else {
                    dsk_min_person.setText("还差" + p_imt + "人");
                }
                goToRefreshView();
                mRx.cancel();
                mRx.interval(1000, next);
            } else {
                TipUtils.showToast(App.getInstance(), "获取活动信息失败");
            }

        } else {
            TipUtils.showToast(App.getInstance(), msg);
        }
    }

    /**
     * 收藏店铺结果
     *
     * @param result
     * @param msg
     */
    @Override
    public void postFavoriteStoreBack(boolean result, String msg) {
        if (result) {
            TipUtils.showToast(App.getInstance(), getString(R.string.home_one_lottery_yyy_favorite_success), 1);
        }
    }

    /**
     * 零钱支付结果
     *
     * @param result
     * @param msg
     * @param map
     */
    @Override
    public void checkDskInfoBack(boolean result, String msg, Map<String, String> map) {
        if (result) {
            presenter.payDskOrder(map);
        } else {
            TipUtils.showToast(App.getInstance(), msg);
        }
    }

    /**
     * 支付返回结果
     *
     * @param result
     * @param msg
     */
    @Override
    public void payDskOrderBack(boolean result, String msg) {
        if (result) {
            RxBus.get().post(new EventBean(Constants.EVENT_TYPE_REFRESH));
            TipUtils.showToast(App.getInstance(), "支付成功", 1);
            finish();
        } else {
            TipUtils.showToast(App.getInstance(), "支付失败: " + msg);
        }
    }


    @Override
    public void getStoreDskInfoBack(boolean result, String msg, List<DskStoreDetailBean.DskStoreDetailItemBean> data) {
        if (result) {
            if (mAdapter == null) {
                mAdapter = new OneLotteryDskAdapter(this, data);
                mRv.setAdapter(mAdapter);
                mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                    @Override
                    public void onLoadMoreRequested() {
                        page++;
                        presenter.getStoreDskInfo(page, entity.getActivity_id());
                    }
                }, mRv);
            } else {
                if (mAdapter.isLoading())
                    mAdapter.loadMoreComplete();
                if (page == 1)
                    mAdapter.replaceData(data);
                else mAdapter.addData(data);
            }
            mAdapter.setEnableLoadMore(data.size() < 100 ? false : true);
            refreshFinish();
        } else {
            TipUtils.showToast(App.getInstance(), msg);
        }

    }

    /**
     * 根据实时时间更新界面
     */
    private void goToRefreshView() {
        int difftime = getDifftime - min_second;
        if (difftime <= 0) {
            tv_time.setText("已结束");
            tv_join.setBackgroundColor(getResources().getColor(R.color.textColorWeak));
        } else {
            int day = difftime / (24 * 60 * 60);
            int hour = (difftime / (60 * 60) - day * 24);
            int min = ((difftime / (60)) - day * 24 * 60 - hour * 60);
            int s = (difftime - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
            String s_min = min + "";
            if (s_min.length() == 1) {
                s_min = "0" + s_min;
            }
            String s_s = s + "";
            if (s_s.length() == 1) {
                s_s = "0" + s_s;
            }
            tv_time.setText(day + "天" + hour + ":" + s_min + ":" + s_s);
        }
    }


    @Override
    protected void onRefreshData() {
        page = 1;
        initInfo();
    }


    @Override
    public void showError(String msg) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAdapter != null && mAdapter.isLoading())
            mAdapter.loadMoreEnd();
        refreshFinish();
    }
}
